package com.ics.atable.chat.controller;

import com.ics.atable.chat.common.BaseResponse;
import com.ics.atable.chat.common.ResultUtils;
import com.ics.atable.chat.model.dto.AddressDTO;
import com.ics.atable.chat.model.dto.AddressEmbeddingDTO;
import com.ics.atable.chat.service.AddressService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 地址管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/address")
@Tag(name = "地址管理", description = "地址相关接口")
public class AddressController {

    @Autowired
    private AddressService addressService;

    /**
     * 上传Excel文件并处理地址数据
     */
    @PostMapping("/upload")
    @Operation(summary = "上传地址Excel并解析", description = "上传包含地址数据的Excel文件，支持.xlsx格式，表头为 org_id, village_name, town_name, city_name, province_name")
    public BaseResponse<List<AddressDTO>> uploadExcel(@RequestParam("file") MultipartFile file) {
        try {
            List<AddressDTO> list = addressService.processExcelFile(file);
            log.info("地址Excel处理成功，共{}条", list.size());
            return ResultUtils.success(list);
        } catch (IllegalArgumentException e) {
            log.error("文件验证失败: {}", e.getMessage());
            return ResultUtils.error(400, e.getMessage());
        } catch (Exception e) {
            log.error("处理地址Excel失败", e);
            return ResultUtils.error(500, "处理地址Excel失败: " + e.getMessage());
        }
    }

    /**
     * 上传Excel，解析并向量化入库
     */
    @PostMapping("/upload/embed")
    @Operation(summary = "上传地址Excel并向量化入库", description = "解析地址Excel，构造addressName/metadata，向量化并写入Milvus")
    public BaseResponse<List<AddressEmbeddingDTO>> uploadExcelAndEmbed(@RequestParam("file") MultipartFile file) {
        try {
            List<AddressEmbeddingDTO> list = addressService.processExcelAndStore(file);
            log.info("地址Excel向量化入库成功，共{}条", list.size());
            return ResultUtils.success(list);
        } catch (IllegalArgumentException e) {
            log.error("文件验证失败: {}", e.getMessage());
            return ResultUtils.error(400, e.getMessage());
        } catch (Exception e) {
            log.error("处理并入库地址Excel失败", e);
            return ResultUtils.error(500, "处理并入库地址Excel失败: " + e.getMessage());
        }
    }
}


